<template>
  <el-upload
    action="http://localhost/api/uploadAvatar"
    :headers="{Authorization: 'Bearer '+token}"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
  <!-- 请找个正方形图片作头像，做不来裁剪 -->
    <el-avatar 
      :src="avatarUrl"
      :size="250"
      title="点击更换头像"
    >
    </el-avatar>
  </el-upload>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
    name: 'AvatarUpload',
    props: ['avatarUrl'],
    setup(props, context) {
        const token = sessionStorage.getItem('token')

        //返回bool值确认上传
        const beforeAvatarUpload = (file) => {
          //console.log(file)
          if(file.type !== 'image/jpeg' && file.type !== 'image/png') {
            ElMessage.error('非法的图片格式！')
            return false
          } else if (file.size / 1024 / 1024 > 3) {
            ElMessage.error('图片大小不能超过3MB!')
            return false
          }
          return true
        }
        const handleAvatarSuccess = (res) => {
          //console.log(res)
          context.emit('updateAvatar', res.url)
          //imageUrl.value = URL.createObjectURL(file.raw)第二个参数file，使用URL生成了一个blob链接，还没搞懂先不用
        }

        return {
          token,
          beforeAvatarUpload,
          handleAvatarSuccess
        }
    }
}
</script>

<style scoped>

</style>